package src.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.zip.DataFormatException;

/**
 * @author CsCN
 */
public class SocketHelper {

    private final Socket socket;
    public String tag;

    public SocketHelper(Socket socket) {
        this.socket = socket;
    }

    public SocketHelper(Socket socket, String tag) {
        this.socket = socket;
        this.tag = tag;
    }

    public void close() throws IOException {
        socket.close();
    }

    /**
     * 通过Socket获得发送来的消息, 并进行解析
     *
     * @param socket socket
     * @return 接收的字符串
     */
    public static String recvString(Socket socket) {
        String rec = null;
        try {
            // 创建输入流, 准备读取字符串
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            rec = (String) ois.readObject();
            // 检查是否为字符串
            if (rec == null) {
                throw new DataFormatException("failed in reading object from socket");
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return rec;
    }

    public String recvString() {
        return recvString(socket);
    }

    /**
     * 通过Socket发送String消息
     *
     * @param message 发送的字符串
     */
    public static void sendString(Socket socket, String message) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendString(String message){
        sendString(socket, message);
    }

    /**
     * 从Socket中接收一个对象, 自己解析
     *
     * @param socket socket
     * @return 接收的对象
     */
    public static Object recvObject(Socket socket) {
        Object o = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            o = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return o;
    }

    /**
     * 通过Socket发送一个对象
     *
     * @param socket socket
     * @param object 要发送的对象
     */
    public static void sendObject(Socket socket, Object object) {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
